<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
            <span v-if="isUpdate">编辑流程模板</span>
            <span v-else>新建流程模板</span>
        </div>
        <el-form
            ref="workflow"
            :rules="rules"
            :model="workflow"
            label-position="right"
            label-width="92px"
        >
            <el-card shadow="never" body-style="padding: 24px;">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="模板名称：" prop="name">
                            <el-input v-model="workflow.name" placeholder style="width:100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="模板类型：" prop="type">
                            <el-select v-model="workflow.type" placeholder="请选择" style="width:100%" filterable>
                                <el-option
                                    v-for="item in options.types"
                                    :key="item.id"
                                    :label="item.typeName"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="审批层级：" prop="level">
                            <el-input-number
                                v-model="workflow.level"
                                :min="1"
                                :max="10"
                                style="width:100%"
                                @change="approveLevelChange"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="培养层次：" prop="listCultureLevel">
                            <el-select
                                v-model="workflow.listCultureLevel"
                                multiple
                                placeholder="请选择"
                                collapse-tags
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.cultureLevels"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="培养类别：">
                            <el-select
                                v-model="workflow.listCultureType"
                                multiple
                                placeholder="请选择"
                                collapse-tags
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.cultureTypes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学位类型：">
                            <el-select
                                v-model="workflow.listDegreeType"
                                multiple
                                placeholder="请选择"
                                collapse-tags
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.degreeTypes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="学位类别：">
                            <el-select
                                v-model="workflow.listDegreeCategory"
                                multiple
                                collapse-tags
                                placeholder="请选择"
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.degreeCategorys"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="国际学生：">
                            <el-select
                                v-model="workflow.isOverseas"
                                placeholder="请选择"
                                style="width:100%"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.overseas"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="学习形式：">
                            <el-select
                                v-model="workflow.listLearning"
                                multiple
                                collapse-tags
                                placeholder="请选择"
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.learnTypes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="专项计划：">
                            <el-select
                                v-model="workflow.listPlan"
                                multiple
                                collapse-tags
                                placeholder="请选择"
                                style="width:100%"
                            >
                                <el-option
                                    v-for="item in options.plans"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item class="is-required scrollbarSty" label="部门：">
                            <edu-transfer
                                :leftChecked="true"
                                :leftFilter="true"
                                leftTitle="所有部门"
                                :leftSearch="true"
                                :rightChecked="true"
                                :rightFilter="true"
                                :selectedBySearch="true"
                                rightTitle="已选择部门"
                                :leftTransferData="leftTransferData"
                                :rightTransferData="rightTransferData"
                                v-on="{addNodesToRight:addNodesToRight,delNodesFromRight:delNodesFromRight}"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-card>

            <div v-for="(listStep,index) in workflow.listStep" :key="index" class="list-step">
                <el-card shadow="never">
                    <div class="edu-page-title">第{{ index+1 }}级审批</div>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="OA单号：" label-width="80px">
                                <el-select
                                    v-model="listStep.needOa"
                                    placeholder="请选择"
                                    style="width:90%"
                                >
                                    <el-option
                                        v-for="item in options.tutorApprovals"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审批组：" label-width="80px">
                                <el-input
                                    :disabled="listStep.need==1 || listStep.specailApproval == 1||listStep.approveType==2 || listStep.approveType==4 || (workflow.type == '11' && index == currentRadioIndex)"
                                    v-model="listStep.approveGroupName"
                                    readonly
                                    placeholder="请选择用户组"
                                    clearable
                                    style="width:90%"
                                    @change="approveGroupChange($event, listStep)"
                                >
                                     <i
                                        slot="suffix"
                                        v-if="listStep.approveGroupName"
                                        class="el-input__icon el-icon-close"
                                        @click="clearGroup(listStep, 'approveGroupName')"
                                    ></i>
                                    <i
                                        slot="suffix"
                                        class="el-input__icon el-icon-more"
                                        @click="selectGroup(1, listStep, index)"
                                    ></i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审批人：" label-width="80px">
                                <el-input
                                    :disabled="listStep.need==1 ||listStep.specailApproval == 1|| listStep.approveType==1 || listStep.approveType==4 || (workflow.type == '11' && index == currentRadioIndex)"
                                    v-model="listStep.approveTeacherName"
                                    readonly
                                    placeholder="请选择审批人"
                                    clearable
                                    style="width:90%"
                                    @change="approverChange($event, listStep)"
                                >
                                    <i
                                        slot="suffix"
                                        v-if="listStep.approveTeacherName"
                                        class="el-input__icon el-icon-close"
                                        @click="clearGroup(listStep, 'approveTeacherName')"
                                    ></i>
                                    <i
                                        slot="suffix"
                                        class="el-input__icon el-icon-more"
                                        @click="selectApprover(listStep, index)"
                                    ></i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="多人会签：" label-width="80px">
                                <el-input
                                    :disabled="listStep.need==1||listStep.specailApproval == 1||listStep.approveType==1 || listStep.approveType==2 ||(workflow.type=='11'&&index==currentRadioIndex)"
                                    v-model="listStep.countersignName"
                                    readonly
                                    placeholder="请选择多人会签"
                                    clearable
                                    style="width:90%"
                                >
                                    <i
                                        slot="suffix"
                                        v-if="listStep.countersignName"
                                        class="el-input__icon el-icon-close"
                                        @click="clearGroup(listStep, 'countersignName')"
                                    ></i>
                                    <i
                                        slot="suffix"
                                        class="el-input__icon el-icon-more"
                                        @click="selectCountersign(listStep, index)"
                                    ></i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="needTutor == 1">
                            <el-form-item label="动态审批：" label-width="80px">
                                <el-select
                                    v-model="listStep.need"
                                    placeholder="请选择"
                                    style="width:90%"
                                    @change="approveTutorChange($event, listStep)"
                                >
                                    <el-option
                                        v-for="item in options.tutorApprovals"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="needSpecial == 1">
                            <el-form-item label="特殊审批：" label-width="80px">
                                <el-select
                                    v-model="listStep.specailApproval"
                                    placeholder="请选择"
                                    style="width:90%"
                                    @change="approveSpecialChange($event, listStep)"
                                >
                                    <el-option
                                        v-for="item in options.tutorApprovals"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="needBusiness == 1">
                            <el-form-item label label-width="20px">
                                <el-radio v-model="currentRadioIndex" :label="index">业务人员</el-radio>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="text-right" style="margin-top:20px">
                <el-button size="medium" @click="cancel">{{ $t('message.cancel') }}</el-button>
                <el-button size="medium" type="primary" @click="commit">提交</el-button>
            </div>
        </el-form>

        <!-- 选择用户组对话框 -->
        <el-dialog 
            :visible.sync="showSelectGroup" 
            :autoHeight=false
            title="选择用户组"
            width="1000px" 
            class="systemDialog scrollbarSty workflow">
            <div style="height: 425px">
                <el-row :gutter="20" style="height:48px;">
                <el-col :span="6" :offset="12">
                    <el-input
                        v-model="groups.params.groupName"
                        placeholder="用户组名称"
                        prefix-icon="el-icon-search"
                        @keyup.enter.native="getGroups"
                    />
                </el-col>
                <el-col :span="6">
                    <el-button @click="getGroups">查询</el-button>
                </el-col>
                </el-row>
                <el-table :data="groups.data.list" 
                    stripe 
                    height="325"
                    tooltip-effect="light"
                    @current-change="handleGroupChange">
                    <el-table-column width="50">
                        <template slot-scope="scope">
                            <el-radio
                                v-model="groups.selectedGroup.groupId"
                                :label="scope.row.groupId"
                            >&nbsp;</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户组名称" width="200" show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.groupName }}</template>
                    </el-table-column>
                    <el-table-column label="备注" show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.description }}</template>
                    </el-table-column>
                </el-table>
                <div class="edu-pagination">
                    <div class="float-right">
                        <el-pagination
                            :current-page="groups.params.pageNum_"
                            :page-sizes="[20,50,100,500,1000]"
                            :page-size="groups.params.pageSize_"
                            :pager-count="5"
                            :total="groups.data.total_"
                            layout="total, sizes, prev, pager, next, jumper"
                            style="float: right;"
                            @size-change="groupPageSizeChange"
                            @current-change="groupCurrentPageChange"
                        />
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="groupConfirmSelection">确 定</el-button>
                <el-button @click="groupCancelSelection">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 选择审批人对话框 -->
        <el-dialog 
            :visible.sync="showSelectApprover" 
            :autoHeight=false
            title="选择审批人" 
            width="1000px" 
            class="systemDialog scrollbarSty workflow">
            <div style="height: 425px">
                <el-form :model="teachers.params" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户组：">
                            <el-input
                                v-model="teachers.selectedGroup.groupName"
                                readonly
                                placeholder="请选择用户组"
                                clearable
                                @change="teacherGroupChange($event)"
                            >
                                <i
                                    slot="suffix"
                                    class="el-input__icon el-icon-more"
                                    @click="selectGroup(2)"
                                ></i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="学院：">
                            <el-select v-model="teachers.params.faculty" style="width:100%">
                                <el-option
                                    v-for="item in options.collages"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item>
                            <el-input
                                v-model="teachers.params.condition"
                                clearable
                                placeholder="工号或者姓名"
                                prefix-icon="el-icon-search"
                                @keyup.enter.native="getTeacherData"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="float-right">
                            <el-button
                                plain
                                @click="resetTeacherCondition"
                            >{{ $t('message.reset') }}</el-button>
                            <el-button plain @click="getTeacherData">{{ $t('message.filter') }}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                </el-form>
                <el-table :data="teachers.data.list" 
                    height="273"
                    stripe 
                    tooltip-effect="light"
                    @current-change="handleTeacherChange">
                    <el-table-column width="50">
                        <template slot-scope="scope">
                            <el-radio
                                v-model="teachers.selectedTeacher.code"
                                :label="scope.row.code"
                            >&nbsp;</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="工号" width="100">
                        <template slot-scope="scope">{{ scope.row.code }}</template>
                    </el-table-column>
                    <el-table-column label="姓名" width="80">
                        <template slot-scope="scope">{{ scope.row.name }}</template>
                    </el-table-column>
                    <el-table-column label="用户组" show-overflow-tooltip width="200">
                        <template slot-scope="scope">{{ scope.row.groupName }}</template>
                    </el-table-column>
                    <el-table-column label="学院" width="180">
                        <template slot-scope="scope">{{ scope.row.facultyI18n }}</template>
                    </el-table-column>
                    <el-table-column label="联系电话" width="150">
                        <template slot-scope="scope">{{ scope.row.telephone }}</template>
                    </el-table-column>
                    <el-table-column label="联系邮箱" width="150">
                        <template slot-scope="scope">{{ scope.row.email }}</template>
                    </el-table-column>
                </el-table>
                <div class="edu-pagination">
                    <div class="float-right">
                        <el-pagination
                            :current-page="teachers.params.pageNum_"
                            :page-sizes="[20,50,100,500,1000]"
                            :page-size="teachers.params.pageSize_"
                            :pager-count="5"
                            :total="teachers.data.total"
                            layout="total, sizes, prev, pager, next, jumper"
                            style="float: right;"
                            @size-change="approverPageSizeChange"
                            @current-change="approverCurrentPageChange"
                        />
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmSelection">确 定</el-button>
                <el-button @click="cancelSelection">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            :visible.sync="showCountersign" 
            :autoHeight=false
            title="多人会签审批" 
            width="1000px" 
            class="systemDialog scrollbarSty workflow">
            <div v-loading="countersignLoading" style="height: 425px">
                <el-form>
                    <el-form-item label="已选审批人：">
                        <el-tag 
                            v-for="tag in countersignSelectedAll"
                            :key="tag"
                            closable 
                            @close="handleClose(tag)">
                            {{tag.name}}
                        </el-tag>
                    </el-form-item>
                </el-form>
                <el-row class="border-bottom" style="margin-top: 10px;padding-bottom: 10px">
                    查询模式：
                    <el-radio-group v-model="queryMode">
                        <el-radio :label="1">学院</el-radio>
                        <el-radio :label="2">工号</el-radio>
                    </el-radio-group>
                    <div class="float-right">
                        <el-button @click="clearSelectAll">清空全部</el-button>
                    </div>
                </el-row>
                <el-row>
                    <div v-if="queryMode == 1">
                        <el-form style="margin-top: 10px;">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="学院:" class="no-bottom">
                                        <el-select
                                            v-model="countersignFaulty.departmentId"
                                            placeholder="选择学院"
                                            @change="changeFaculty"
                                            filterable
                                            style="width: 90%"
                                        >
                                            <el-option
                                                v-for="item in options.collages"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-button  
                                        type="button"
                                        @click="addSelectCountersign">添加</el-button>
                                </el-col>
                            </el-row>
                        </el-form>
                        <edu-table 
                            :data="countersignData" 
                            :total="countersignPagination.total"
                            :pageNum="countersignPagination.pageNum_"
                            :pageSize="countersignPagination.pageSize_" 
                            :order="false" 
                            :selection="true"
                            height="210"
                            ref="countersignTable"
                            @select-all="handleSelectAll"
                            @selection-change="handleSelectionChange"
                            @page-change="countersignPageChange">
                                <edu-table-column :label="countersignTable.id" prop="id"/>
                                <edu-table-column :label="countersignTable.name" prop="name"/>
                        </edu-table>
                    </div>
                    <div v-if="queryMode == 2">
                        <div class="user-select-box" style="margin-top: 10px;">
                            <el-select
                                v-model="chosedUser"
                                :remote-method="selectUser"
                                placeholder="工号搜索"
                                filterable
                                clearable
                                remote
                                size="mini"
                                style="width:160px;">
                                <el-option
                                    v-for="item in staffData"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"/>
                            </el-select>
                            <i
                                slot="suffix"
                                class="el-icon-search"/>
                            <el-button
                                style="margin-left: 20px;"
                                type="button"
                                @click="addCountersign">添加</el-button>
                        </div>
                    </div>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmCountersignSelection">确 定</el-button>
                <el-button @click="cancelCountersignSelection">取 消</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import {
    getGroups,
    getGroupById,
    findAllDeptList,
    findTopTenTeacherList,
    findTeacherInfoBycode,
    findTeacherInfoListInGroupId
} from "common/src/api/user";
import { queryDic } from "common/src/api/dictionary";
import WorkflowApi from "common/src/api/workflow";
import EduTransfer from "common/src/components/common/EduTransfer";

export default {
    name: "workflow",
    components: { EduTransfer },
    data: function() {
        const step = {
            approveType: 3,
            approveRoleId: "",
            approveGroup: {},
            approveGroupName: "",
            approveTeacher: {},
            approveTeacherName: "",
            countersign: {},
            countersignName: '',
            need: "2",
            specailApproval: '2',
            stepType: "",
            needOa: "2"
        };

        let that = this;
        return {
            leftTransferData: "",
            rightTransferData: "",
            isUpdate: false,
            defaultProps: {
                children: "children",
                label: "label"
            },
            groups: {
                pageType: 1, // 1:从创建流程管理页面打开 2：从选择指定审核人页面打开
                params: {
                    groupName: "",
                    pageNum_: 1,
                    pageSize_: 20
                },
                data: [],
                selectedGroup: {},
                defaultGroup: {
                    groupId: "",
                    groupName: ""
                }
            },
            departments: [],
            leftDepartments: [],
            rightDepartments: [],
            fromDepData: [],
            toDepData: [],
            teachers: {
                params: {
                    groupId: "",
                    faculty: "",
                    condition: "",
                    pageNum_: 1,
                    pageSize_: 20
                },
                selectedGroup: {},
                selectedTeacher: {},
                data: []
            },
            currentRadioIndex: -1,
            currentStep: {},
            step: step,
            workflow: {
                name: "",
                type: "",
                level: 3,
                listCultureLevel: [],
                listCultureType: [],
                listDegreeType: [],
                listDegreeCategory: [],
                isOverseas: null,
                listLearning: [],
                listPlan: [],
                listStep: [
                    JSON.parse(JSON.stringify(step)),
                    JSON.parse(JSON.stringify(step)),
                    JSON.parse(JSON.stringify(step))
                ]
            },
            showSelectGroup: false,
            showSelectApprover: false,
            options: {
                types: [],
                cultureLevels: [],
                cultureTypes: [],
                degreeCategorys: [],
                degreeTypes: [],
                learnTypes: [],
                plans: [],
                overseas: [
                    { label: "是", value: 2 },
                    { label: "否", value: 1 }
                ],
                tutorApprovals: [
                    { label: "需要", value: "1" },
                    { label: "不需要", value: "2" }
                ],
                collages: []
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入模板名称！"
                    }
                ],
                type: [
                    {
                        required: true,
                        message: "请选择模板类型！"
                    }
                ],
                level: [
                    {
                        required: true,
                        message: "请输入审批层级！"
                    }
                ],
                listCultureLevel: [
                    {
                        required: true,
                        message: "请选择培养层次！"
                    }
                ]
            },
            categories: {
                cultureLevels: "X_PYCC",
                cultureTypes: "X_PYLB",
                degreeTypes: "X_XWLX",
                degreeCategorys: "X_XWLB",
                learnTypes: "X_XXXS",
                plans: "X_ZXJH",
                X_YX: "X_YX"
            },
            showCountersign: false,
            countersignLoading: false,
            queryMode: 1,
            countersignSelected: [],
            countersignSelectedAll: [],
            countersignSelectedName: [],
            countersignSelectedNameStep: [],
            countersignData: [
                {
                    id: 1,
                    name: 123
                },
                {
                    id: 2,
                    name: 1234
                }
            ],
            countersignTable: {
                id: '工号',
                name: '姓名'
            },
            countersignPagination: {
                pageNum_: 1,
                pageSize_: 20,
                total: ''
            },
            countersignFaulty: {
                departmentId: ''
            },
            staffData: [],
            chosedUser: '',
            currentActionStep: 0
        };
    },
    watch: {
        currentRadioIndex: function(_new, _old) {
            console.log(_new, _old)
            this.workflow.listStep[_new] = JSON.parse(
                JSON.stringify(this.step)
            );
            this.workflow.listStep[_new].approveType = 3;
            this.workflow.listStep[_old].approveType = 0;

            // 深复制达到强制刷新的效果
            this.workflow.listStep = JSON.parse(
                JSON.stringify(this.workflow.listStep)
            );
        }
    },
    computed: {
        needTutor() {
            return this.options.types
                .filter(item => {
                    return this.workflow.type == item.id;
                })
                .map(item => {
                    return item.needTutor;
                });
        },
        needBusiness() {
            return this.options.types
                .filter(item => {
                    return this.workflow.type == item.id;
                })
                .map(item => {
                    return item.needBusiness;
                });
        },
        needSpecial() {
            return this.options.types
                .filter(item => {
                    return this.workflow.type == item.id;
                })
                .map(item => {
                    return item.needSpecial;
                });
        }
    },
    mounted() {
        this.getOptions();
        this.isUpdate = this.$route.params.hasOwnProperty("templateId");
        if (!this.isUpdate) {
            this.$refs["workflow"].resetFields();
        }

        this.getDepartments().then(searchResult => {
            if (searchResult) {
                // 更新页面
                this.leftTransferData = JSON.stringify(this.departments);
                this.rightTransferData = "";
                if (this.isUpdate) {
                    this.getTemplate();
                }
            }
        });
        console.log(window.document.clientHeight)
        console.log((window.innerHeight - 600) / 1200)
    },
    methods: {
        addNodesToRight({ rightUpdateData, leftUpdateData }) {
            this.rightTransferData = rightUpdateData;
            this.leftTransferData = leftUpdateData;
        },
        delNodesFromRight({ rightUpdateData, leftUpdateData }) {
            this.rightTransferData = rightUpdateData;
            this.leftTransferData = leftUpdateData;
        },
        validateApprover(workflow) {
            let valid;
            for (let index = 0; index < workflow.listStep.length; index++) {
                const item = workflow.listStep[index];
                console.log(item)
                if (item.approveType == 0 && item.need == "1") {
                    // 导师审批
                    valid = "0";
                } else if (item.approveType == 5 && item.specailApproval == "1") {
                    // 特殊审批
                    valid = "0";
                } else if (item.approveRoleId && item.approveRoleId != "") {
                    // 用户组或者指定审批人审批
                    valid = "0";
                } else if (index == this.currentRadioIndex) {
                    // 业务人员
                    valid = "0";
                } else {
                    this.$message({
                        type: "warning",
                        message: `请选择第${index + 1}级审批人！`
                    });
                    valid = "1";
                    break;
                }
            }
            return valid == "0";
        },
        getOptions() {
            // 查询模板类型
            WorkflowApi.selectTemplateType().then(response => {
                if (response.code == 200) {
                    this.options.types = response.data;
                }
            });
            // 从数据字典查询其他选项
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "X_PYCC",
                    "X_PYLB",
                    "X_XWLX",
                    "X_XWLB",
                    "X_XXXS",
                    "X_ZXJH",
                    "X_YX"
                ]
            };
            queryDic(data).then(response => {
                if (response.code === 200) {
                    const makeOptions = function(type) {
                        if (response.data && response.data[type]) {
                            const items = [];
                            for (var key in response.data[type]) {
                                items.push({
                                    value: String(key),
                                    label: response.data[type][key]
                                });
                            }
                            return items;
                        }

                        return [];
                    };

                    // for (let key in this.categories) {
                    //   this.options[key] = this.options[key].concat(
                    //     makeOptions(this.categories[key])
                    //   );
                    // }
                    // 培养层次
                    this.options.cultureLevels = this.options.cultureTypes.concat(
                        makeOptions("X_PYCC")
                    );
                    // 培养类别
                    this.options.cultureTypes = this.options.cultureTypes.concat(
                        makeOptions("X_PYLB")
                    );
                    // 学位类型
                    this.options.degreeTypes = this.options.degreeTypes.concat(
                        makeOptions("X_XWLX")
                    );
                    // 学位类别
                    this.options.degreeCategorys = this.options.degreeCategorys.concat(
                        makeOptions("X_XWLB")
                    );
                    // 学习形式
                    this.options.learnTypes = this.options.learnTypes.concat(
                        makeOptions("X_XXXS")
                    );
                    // 专项计划
                    this.options.plans = this.options.plans.concat(
                        makeOptions("X_ZXJH")
                    );
                    // 学院
                    this.options.collages = this.options.collages.concat(
                        makeOptions("X_YX")
                    );
                }
            });
        },
        cancel() {
            this.$router.push("/workflow");
        },
        commit() {
            // 校验用户是否选择完整的信息，并提交
            this.$refs["workflow"].validate(valid => {
                if (!valid) {
                    this.$message({
                        type: "warning",
                        message: "信息输入不完整，请完善信息后重试!"
                    });
                    return false;
                } else {
                    const workflow = JSON.parse(JSON.stringify(this.workflow));
                    // 部门
                    if (this.rightTransferData.length) {
                        workflow.listDepartement = JSON.parse(
                            this.rightTransferData
                        ).map(item => {
                            return item.deptCode;
                        });
                        
                    }
                    if (!(workflow.listDepartement && workflow.listDepartement.length)) {
                        this.$message({
                            type: "warning",
                            message: "请选择部门信息后重试!"
                        });
                        return;
                    }

                    // 审批层级数据
                    workflow.listStep = this.workflow.listStep.map(
                        (item, index) => {
                            if (item.approveType == 0) {
                                // 导师审批
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: "",
                                    need: item.need,
                                    needOa: item.needOa,
                                    stepType: index + 1
                                };
                            } else if (item.approveType == 1) {
                                // 用户组审批
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: item.approveGroup.groupId,
                                    need: item.need,
                                    needOa: item.needOa,
                                    stepType: index + 1
                                };
                            } else if (item.approveType == 2) {
                                // 指定审核人
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: item.approveTeacher.code,
                                    need: item.need,
                                    needOa: item.needOa,
                                    stepType: index + 1
                                };
                            } else if (item.approveType == 4) {
                                // 
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: item.countersign.join(','),
                                    approveRoleName: item.countersignName.join(','),
                                    need: item.need,
                                    needOa: item.needOa,
                                    stepType: index + 1
                                };
                            }  else if (item.approveType == 5) {
                                // 特殊审批
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: "",
                                    need: 2,
                                    needOa: item.needOa,
                                    specailApproval: item.specailApproval,
                                    stepType: index + 1
                                };
                            } else {
                                // 指定审核人
                                return {
                                    approveType: item.approveType,
                                    approveRoleId: "",
                                    need: item.need,
                                    needOa: item.needOa,
                                    stepType: index + 1
                                };
                            }
                        }
                    );
                    console.log(workflow);
                    // 校验是否选择审批人
                    if (!this.validateApprover(workflow)) {
                        return;
                    }
                    if (workflow.isOverseas == '') {
                        workflow.isOverseas = null;
                    }
                    if (this.isUpdate) {
                        this.updateWorkflow(workflow);
                    } else {
                        this.createWorkflow(workflow);
                    }
                }
            });
        },
        createWorkflow(workflow) {
            WorkflowApi.addTemplate(workflow)
                .then(
                    response => {
                        if (response.code == 200) {
                            this.$router.push("/workflow");
                            this.$message({
                                type: "success",
                                message: response.msg
                            });
                        } else {
                            this.$message({
                                type: "error",
                                message: response.msg
                            });
                        }
                    },
                    error => {
                        this.$message({
                            type: "error",
                            message: "创建模板失败，请刷新后重试！"
                        });
                    }
                )
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "创建模板失败，请刷新后重试！"
                    });
                });
        },
        updateWorkflow(workflow) {
            WorkflowApi.updateTemplate(workflow).then(response => {
                if (response.code == 200) {
                    this.$router.push("/workflow");
                    this.$message({
                        type: "success",
                        message: response.msg
                    });
                } else if (response.code == 302) {
                    this.$alert(response.msg, '提示', {
                        showCancelButton: true
                    }).then((action) => {
                        if (action === 'confirm') {
                            WorkflowApi.updateTemplateReject(workflow).then(response => {
                                if (response.code == 200) {
                                    this.updateWorkflow(workflow);
                                }
                            })
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '取消继续更新'
                        });
                    })
                } else {
                    this.$message({
                        type: "error",
                        message: response.msg
                    });
                }
            });
        },
        approveLevelChange(approveLevel) {
            if (approveLevel < this.workflow.listStep.length) {
                // 删除审批层次
                while (this.workflow.listStep.length > approveLevel) {
                    this.workflow.listStep.pop();
                }
            } else if (approveLevel > this.workflow.listStep.length) {
                // 增加审批层次
                while (this.workflow.listStep.length < approveLevel) {
                    this.workflow.listStep.push(
                        JSON.parse(JSON.stringify(this.step))
                    );
                }
            }
        },
        getDepartments() {
            return findAllDeptList(1).then(response => {
                if (response.code == 200) {
                    this.departments = response.data;
                }
                return this.departments.length > 0;
            });
        },
        getGroups() {
            return getGroups(this.groups.params).then(response => {
                if (response.code == 200) {
                    this.groups.data = response.data;
                }
            });
        },
        getAllTeachers() {
            this.teachers.params.groupId = this.teachers.selectedGroup.groupId;
            findTeacherInfoListInGroupId(this.teachers.params).then(
                response => {
                    if (response.code == 200) {
                        this.teachers.data = response.data;
                    }
                }
            );
        },
        approveTutorChange(need, stepData) {
            if (need == "1") {
                stepData.approveType = 0;
                stepData.approveGroupName = ''
                stepData.approveTeacherName = ''
                stepData.countersignName = ''
                stepData.specailApproval = '2'
            } else if (
                stepData.approveGroupName &&
                stepData.approveGroupName != ""
            ) {
                stepData.approveType = 1;
            } else if (
                stepData.approveTeacherName &&
                stepData.approveTeacherName != ""
            ) {
                stepData.approveType = 2;
            }
        },
        approveSpecialChange(need, stepData) {
            if (need == "1") {
                stepData.approveType = 5;
                stepData.approveGroupName = ''
                stepData.approveTeacherName = ''
                stepData.countersignName = ''
                stepData.need = '2'
            } else if (
                stepData.approveGroupName &&
                stepData.approveGroupName != ""
            ) {
                stepData.approveType = 1;
            } else if (
                stepData.approveTeacherName &&
                stepData.approveTeacherName != ""
            ) {
                stepData.approveType = 2;
            }
        },
        approveGroupChange(group, stepData) {
            stepData.approveType = group == "" ? 0 : 1;
        },
        selectGroup(type, listStep) {
            const args = Array.slice(arguments);
            if (type == 1) {
                this.currentStep = listStep;
                if (
                    listStep.need == 1 ||
                    listStep.approveType == 2 || listStep.approveType == 4 ||
                    (args.length == 3 &&
                        args[2] == this.currentRadioIndex &&
                        this.workflow.approveType == 11)
                ) {
                    return;
                }
            }
            this.groups.pageType = type;
            this.showSelectGroup = true;
            this.getGroups();
        },
        clearGroup(listStep, inputName) {
            console.log(listStep);
            listStep[inputName] = "";
            listStep.need = 2;
            listStep.specailApproval = 2;
            listStep.approveType = 3;
        },
        handleGroupChange(row) {
            if (row) {
                this.groups.selectedGroup = row;
            } else {
                this.groups.selectedGroup = {};
            }
        },
        groupPageSizeChange(pageSize) {
            this.groups.params.pageSize_ = pageSize;
            this.getGroups();
        },
        groupCurrentPageChange(currentPage) {
            this.groups.params.pageNum_ = currentPage;
            this.getGroups();
        },
        groupCancelSelection() {
            this.groups.selectedGroup = {};
            this.showSelectGroup = false;
        },
        groupConfirmSelection() {
            if (this.groups.pageType == 1) {
                this.currentStep.approveType = 1;
                this.currentStep.approveGroup = this.groups.selectedGroup;
                this.currentStep.approveGroupName = this.groups.selectedGroup.groupName;
            } else {
                this.teachers.selectedGroup = this.groups.selectedGroup;
            }
            this.groups.selectedGroup = {};
            this.showSelectGroup = false;
        },
        approverChange(val, stepData) {
            stepData.approveType = val == "" ? 0 : 2;
        },
        selectApprover(listStep) {
            const args = Array.slice(arguments);
            if (
                listStep.need == 1 ||
                listStep.approveType == 1 || listStep.approveType == 4 ||
                (args.length == 2 &&
                    args[1] == this.currentRadioIndex &&
                    this.workflow.approveType == 11)
            ) {
                return;
            }
            this.currentStep = listStep;
            this.showSelectApprover = true;
            this.getAllTeachers();
        },
        teacherGroupChange(group) {
            if (group == "") {
                this.teachers.selectedGroup = this.groups.defaultGroup;
            }
        },
        resetTeacherCondition() {
            this.teachers.selectedGroup = this.groups.defaultGroup;
            this.teachers.params.groupId = "";
            this.teachers.params.faculty = "";
            this.teachers.params.condition = "";
            this.teachers.params.pageNum_ = 1;
            this.teachers.params.pageSize_ = 20;
            this.getAllTeachers();
        },
        getTeacherData() {
            this.getAllTeachers();
        },
        handleTeacherChange(row) {
            if (row) {
                this.teachers.selectedTeacher = row;
            } else {
                this.teachers.selectedTeacher = {};
            }
        },
        approverPageSizeChange(pageSize) {
            this.teachers.params.pageSize_ = pageSize;
            this.getTeacherData();
        },
        approverCurrentPageChange(currentPage) {
            this.teachers.params.pageNum_ = currentPage;
            this.getTeacherData();
        },
        cancelSelection() {
            this.teachers.selectedTeacher = {};
            this.showSelectApprover = false;
        },
        confirmSelection() {
            this.currentStep.approveType = 2;
            this.currentStep.approveTeacher = this.teachers.selectedTeacher;
            this.currentStep.approveTeacherName = this.teachers.selectedTeacher.name;
            this.showSelectApprover = false;
        },
        switchToFormData(response) {
            const tempWorkflow = response.data;
            // 部门
            let ids = tempWorkflow.listDepartement.map(item => {
                return item.departmentId;
            });
            let rightTransferData = JSON.parse(this.leftTransferData).filter(
                item => {
                    if (ids.indexOf(item.deptCode) > -1) {
                        return item;
                    }
                }
            );
            this.rightTransferData = JSON.stringify(rightTransferData);
            // 模板类型
            tempWorkflow.type = parseInt(tempWorkflow.type);
            // 学习方式
            tempWorkflow.listLearning = tempWorkflow.listLearning.map(item => {
                return item.learningId;
            });
            // 学位类型
            tempWorkflow.listDegreeType = tempWorkflow.listDegreeType.map(
                item => {
                    return item.degreeTypeId;
                }
            );
            // 学位类别
            tempWorkflow.listDegreeCategory = tempWorkflow.listDegreeCategory.map(
                item => {
                    return item.degreeCategoryId;
                }
            );
            // 培养层次
            tempWorkflow.listCultureLevel = tempWorkflow.listCultureLevel.map(
                item => {
                    return item.cultureLevelId;
                }
            );
            // 培养类型
            tempWorkflow.listCultureType = tempWorkflow.listCultureType.map(
                item => {
                    return item.clutureTypeId;
                }
            );
            // 专项计划
            tempWorkflow.listPlan = tempWorkflow.listPlan.map(item => {
                return item.planId;
            });
            // 审批等级
            tempWorkflow.listStep.forEach((item, idx) => {
                if (item.approveType == 2) {
                    // 查询审批人的名字
                    const teacherId = item.approveRoleId;
                    item.approveRoleId = "";
                    item.approveTeacher = {};
                    item.approveTeacherName = "";
                    if (teacherId) {
                        findTeacherInfoBycode(teacherId).then(response => {
                            if (response.code == 200) {
                                item.approveTeacher = response.data;
                                item.approveTeacherName =
                                    response.data.name || "";
                            }
                        });
                    }
                } else if (item.approveType == 1) {
                    // 用户组
                    const groupId = item.approveRoleId;
                    item.approveRoleId = "";
                    item.approveGroup = {};
                    item.approveGroupName = "";
                    if (groupId) {
                        getGroupById(groupId).then(response => {
                            if (response.code == 200) {
                                item.approveGroup = response.data;
                                item.approveGroupName =
                                    response.data.groupName || "";
                            }
                        });
                    }
                } else if (item.approveType == 4) {
                    let ids = item.approveRoleId ? item.approveRoleId.split(',') : [];
                    let names = item.approveRoleName ? item.approveRoleName.split(',') : [];
                    this.countersignSelected[idx] = [];
                    ids.forEach((item, index) => {
                        this.countersignSelected[idx].push({
                            id: item,
                            name: names[index]
                        })
                    });
                    item.approveRoleId = "";
                    item.countersign = {};
                    item.countersignName = "";
                    
                    item.countersign = ids;
                    item.countersignName = names;
                }  else if (item.approveType == 5) {
                    item.specailApproval = '1'
                } else {
                    item.approveRoleId = "";
                }
                if (item.approveType == 3) {
                    this.currentRadioIndex = idx;
                }
                if (item.approveType !== 5) {
                    item.specailApproval = '2'
                }
            });
            return tempWorkflow;
        },
        getTemplate() {
            const queryParams = {
                id: this.$route.params.templateId
            };
            WorkflowApi.selectTemplateDetail(queryParams)
                .then(response => {
                    if (response.code === 200) {
                        this.workflow = this.switchToFormData(response);
                    } else {
                        throw response.msg;
                    }
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: error
                    });
                });
        },
        getAllSigners() {
            this.countersignLoading = true;
            findTeacherInfoListInGroupId({
                condition: '',
                faculty: this.countersignFaulty.departmentId,
                pageNum_: this.countersignPagination.pageNum_,
                pageSize_: this.countersignPagination.pageSize_
            }).then(res => {
                if (res && res.code == 200) {
                    this.countersignData = []
                    if (res.data && res.data.list) {
                        res.data.list.forEach(item => {
                            this.countersignData.push({
                                id: item.code,
                                name: item.name,
                            })
                        })
                        this.countersignPagination.total = res.data.total;
                        this.countersignLoading = false;
                    }
                }
            }).catch(error => {
                this.countersignLoading = false;
            });
        },
        handleClose(tag) {
            this.countersignSelectedAll.splice(this.countersignSelectedAll.indexOf(tag), 1);
            let removeTarget = this.countersignData[this.countersignData.indexOf(tag)];
            console.log(removeTarget);
            this.$refs.countersignTable.$refs.tableRef.toggleRowSelection(removeTarget, false);
        },
        onCurrentPageChange() {

        },
        handleSelectionChange(selection) {
            this.selectedSignData = selection;
        },
        handleSelectAll(selection) {
            console.log(selection)
        },
        handleSelect(selection, row) {
            // if (selection.length) {
            //     if (!this.countersignSelectedAll.some(item => item.id == row.id)) {
            //         this.countersignSelectedAll = this.countersignSelectedAll.concat(row)
            //     }
            // }
            // if (this.countersignSelectedAll.length > 10) {
            //     this.$alert('超过审批人上限（多人会签最大审批人数为10人）', null, {
            //         type: 'warning'
            //     })
            //     this.countersignSelectedAll.length = 10;
            // }
        },
        addSelectCountersign() {
            if (this.selectedSignData.length) {
                this.selectedSignData.forEach(sign => {
                    if (!this.countersignSelectedAll.some(item => item.id == sign.id)) {
                        this.countersignSelectedAll = this.countersignSelectedAll.concat(sign)
                    }
                })
            }
            // if (selection.length) {
            //     if (!this.countersignSelectedAll.some(item => item.id == row.id)) {
            //         this.countersignSelectedAll = this.countersignSelectedAll.concat(row)
            //     }
            // }
            if (this.countersignSelectedAll.length > 10) {
                this.$alert('超过审批人上限（多人会签最大审批人数为10人）', null, {
                    type: 'warning'
                })
                this.countersignSelectedAll.length = 10;
            }
        },
        countersignPageChange(page) {
            this.countersignPagination.pageSize_ = page.pageSize;
            this.countersignPagination.pageNum_ = page.currentPage;
            this.getAllSigners();
        },
        changeFaculty() {
            this.getAllSigners();
        },
        selectUser(query) {
            if (!query) return;
            const data = { userId: query };
            this.loading = true;
            findTopTenTeacherList(data).then(res => {
                this.loading = false;
                if (res.code == 200) {
                    this.userList = res.data;
                    this.staffData = this.transData(res.data);
                    console.log(this.staffData);
                } else {
                    throw res.code;
                }
            }).catch(error => {
                this.loading = false;
                this.$message({
                    type: "error",
                    message: "查询用户出错"
                });
            });
        },
        transData(list) {
            return list.map((item, index, array) => {
                return {
                    label: item.userName + "(" + item.userId + ")",
                    value: `${item.userId}_${item.userName}`
                };
            });
        },
        addCountersign() {
            if (!this.chosedUser) {
                return;
            }
            let id = this.chosedUser.split('_')[0];
            let name = this.chosedUser.split('_')[1];
            let signer = {
                id: id,
                name: name
            }
            if (!this.countersignSelectedAll.some(item => item.id == id)) {
                this.countersignSelectedAll = this.countersignSelectedAll.concat(signer);
            } else {
                this.$alert('该审批人已添加过', null, {
                    type: 'warning'
                })
            }
            if (this.countersignSelectedAll.length > 10) {
                this.$alert('超过审批人上限（多人会签最大审批人数为10人）', null, {
                    type: 'warning'
                })
                this.countersignSelectedAll.length = 10;
                return;
            }
            this.chosedUser = '';
        },
        selectCountersign(listStep, step) {
            const args = Array.slice(arguments);
            if (
                listStep.need == 1 ||
                listStep.approveType == 1 || listStep.approveType == 2 ||
                (args.length == 2 &&
                    args[1] == this.currentRadioIndex &&
                    this.workflow.approveType == 11)
            ) {
                return;
            }
            this.queryMode = 1;
            this.currentStep = listStep;
            this.showCountersign = true;
            this.currentActionStep = step;
            this.countersignSelectedName = [];
            if (this.countersignSelected[this.currentActionStep]) {
                this.countersignSelectedAll = this.countersignSelected[this.currentActionStep];
            } else {
                this.countersignSelectedAll = [];
            }
            this.getAllSigners(step);
        },
        confirmCountersignSelection() {
            if (this.countersignSelectedAll) {
                this.currentStep.approveType = this.countersignSelectedAll.length
                    ? 4
                    : 3;
                // if (this.currentStep.countersign.length) {
                //     this.countersignSelectedName = this.countersignSelectedName.concat(this.currentStep.countersignName);
                // }
                // this.currentStep.countersign = this.countersignSelectedAll;
                // this.countersignSelectedAll.forEach(item => {
                //     let index = _.findIndex(this.countersignData, (it) => {
                //         return it.id === item.id
                //     })
                //     if (index != -1) {
                //         this.countersignSelectedName.push(this.countersignData[index].name)
                //     }
                // })
                // this.currentStep.countersignName = this.countersignSelectedName;
                this.currentStep.countersign = [];
                this.currentStep.countersignName = [];
                this.countersignSelectedAll.forEach(item => {
                    this.currentStep.countersign.push(item.id);
                    this.currentStep.countersignName.push(item.name);
                });
                this.countersignSelectedNameStep[this.currentActionStep] = this.countersignSelectedName;
            }
            this.countersignSelected[this.currentActionStep] = this.countersignSelectedAll;
            this.showCountersign = false;
            this.countersignLoading = false;
        }, 
        cancelCountersignSelection() {
            this.showCountersign = false;
            this.countersignLoading = false;
        },
        clearSelectAll() {
            this.countersignSelectedAll = [];
        }
    }
};
</script>
<style lang="scss" scoped>
.list-step {
    border-top: 16px solid rgb(235, 238, 245);
    .el-card {
        border: 0px;
        padding-bottom: 24px;
    }
    .edu-page-title {
        font-family: PingFangSC-Medium;
        font-size: 16px;
        color: #2b3b4e;
        letter-spacing: 0;
        line-height: 16px;
    }
    .el-row {
        .el-col {
            margin-top: 16px;
            height: 30px;
        }
    }
    .el-input__icon {
        cursor: pointer;
    }
}
.systemDialog .el-form-item__content .el-tag{
    margin-right: 5px;
}
</style>
